package com.example.applemusicauth_plugin_t;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.apple.android.sdk.authentication.AuthenticationFactory;
import com.apple.android.sdk.authentication.AuthenticationManager;
import com.apple.android.sdk.authentication.TokenError;
import com.apple.android.sdk.authentication.TokenResult;

import java.util.HashMap;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;

/**
 * ApplemusicauthPlugin_tPlugin
 */
public class ApplemusicauthPlugin_tPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware, PluginRegistry.ActivityResultListener {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private MethodChannel channel;

    /**
     * 用来获取当前Context
     */
    private Activity activity;

    private AuthenticationManager authenticationManager;
    private static final int REQUESTCODE_APPLEMUSIC_AUTH = 3456;

    Result getAppleMusicAuthResult;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "applemusicauth_plugin_t");
        channel.setMethodCallHandler(this);
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        if (call.method.equals("getPlatformVersion")) {
            result.success("Android " + android.os.Build.VERSION.RELEASE);
        } else if (call.method.equals("getAppleMusicAuth")) {
            HashMap argumentsMap = (HashMap) call.arguments;
            String developerToken = argumentsMap.get("developerToken").toString();
            getAppleMusicAuthResult = result;
            userAuth(developerToken);

        } else if (call.method.equals("getAppleMusic")) {
            HashMap argumentsMap = (HashMap) call.arguments;
            String packageName = argumentsMap.get("baoName").toString();
            boolean has = checkAppInstalled(activity,packageName);
            HashMap map = new HashMap();
            map.put("appleMusic",has ? "1" : "0");
            result.success(map);
        }
        else {
            result.notImplemented();
        }
    }

    private boolean checkAppInstalled(Context context, String packageName) {
        if (packageName== null || packageName.isEmpty()) {
            return false;
        }
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        //true为安装了，false为未安装
        return packageInfo != null;
    }

    public void userAuth(String developerToken) {

        authenticationManager = AuthenticationFactory.createAuthenticationManager(activity);
        Intent intent = authenticationManager.createIntentBuilder(developerToken)
                .setHideStartScreen(false)
                .setStartScreenMessage("To play the full song, connect CustomMusicPlayer to Apple Music. (Can be replaced by third party app's custom text message)")
                //set this if you want to set custom params
//            .setCustomParams(params)
                // set this if you want to have contextual upsell
//            .setContextId("1100742453")
                // invoke build to generate the intent, make sure to use startActivityForResult if you care about the music-user-token being returned.
                .build();
        activity.startActivityForResult(intent, REQUESTCODE_APPLEMUSIC_AUTH);
    }

    @Override
    public boolean onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUESTCODE_APPLEMUSIC_AUTH) {
            TokenResult tokenResult = authenticationManager.handleTokenResult(data);
            HashMap map = new HashMap();
            if (!tokenResult.isError()) {
                String musicUserToken = tokenResult.getMusicUserToken();
                System.out.println("取得的musicUserToken = " + musicUserToken);
                map.put("userToken",musicUserToken);
                if (getAppleMusicAuthResult != null) {
                    getAppleMusicAuthResult.success(map);
                    return true;
                }
            } else {
                TokenError error = tokenResult.getError();
                System.out.println("错误 error = " + error.toString());
            }

            getAppleMusicAuthResult.success(map);
        }
        return false;
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    /**
     * ActivityAware 用来获取Context applicationContext = activity.getApplicationContext()
     */
    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        binding.addActivityResultListener(this);
        activity = binding.getActivity();
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {
        this.onDetachedFromActivity();
    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
        this.onAttachedToActivity(binding);
    }

    @Override
    public void onDetachedFromActivity() {
        activity = null;
    }


}
